package io_demo;

/**
 * @author ChenYongHao
 * @date 2023/4/28 10:41
 * @desc IO 异常捕获  捕获异常新特性
 */

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

//JDK7以前做法
public class IO_Exception_Demo {
    public static void main(String[] args) {
        method();
    }

    private static void method() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("fr.txt");
            fw = new FileWriter("fw.txt");
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//JDK7版本改进
class Main {
    public static void main(String[] args) {
        method();
    }

    private static void method() {
        try (FileReader fr = new FileReader("fr.txt");
             FileWriter fw = new FileWriter("fw.txt");) {
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
